package com.hyacinth.core.sysmgr.domain;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import com.hyacinth.common.framework.Domain;
import com.hyacinth.common.jpql.SimpleJPQL;
import com.hyacinth.common.jpql.reserved.Comparation;
import com.hyacinth.common.util.Md5;

@Entity
@Table(name="sys_user")
public class SysUser extends Domain {

	private static final long serialVersionUID = -214189416346384651L;
	
	private String username;
	private String password;
	private Set<SysRole> roles = new HashSet<SysRole>();
	
	
	public SysUser login() {
		SimpleJPQL jpql = new SimpleJPQL(this.getClass());
		this.password = Md5.encrypt(password);
		jpql.where().add("username", Comparation.EQUAL, username);
		SysUser tUser = (SysUser)jpql.single();
		if(tUser!=null) {
			if(tUser.getPassword().equals(password))
				return tUser;
		}
		return null;
	}
	
	public int save() {
		this.persist();
		return 0;
	}
	
	public void logout() {
	}
	
	@Column(length=20, nullable=false)
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	@Column(length=40, nullable=false)
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	@OneToMany(fetch=FetchType.EAGER)
	@JoinTable(name="sys_user_role",joinColumns=@JoinColumn(name="user_id"),inverseJoinColumns=@JoinColumn(name="role_id"))
	public Set<SysRole> getRoles() {
		return roles;
	}

	public void setRoles(Set<SysRole> roles) {
		this.roles = roles;
	}
}
